package com.xuecheng.gateway.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class AuthFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String jsonToken = request.getHeader("Authorization");
        if(!StringUtils.isEmpty(jsonToken) ){
            if(jsonToken.startsWith("Bearer ")){
                jsonToken = jsonToken.substring(7);
                ctx.addZuulRequestHeader("jsonToken", jsonToken);
            }else{
                throw new RuntimeException("token is not as expected");
            }
        }
        return null;
    }
}
